package com.ms.yk;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ms.yk.service.SmsObserverService;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class LoginActivity extends BaseActivity {
    private EditText etUser, etPsw;
    private SharedPreferences sharedPreferences;
    private String user, psw;

    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        etUser = findViewById(R.id.et_user);
        etPsw = findViewById(R.id.et_psw);
        findViewById(R.id.ll_content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeKeyboard();
            }
        });
    }

    @Override
    public void initData() {
        SmsApplication.removeActivityExist(this);

        sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
        user = sharedPreferences.getString("username", "");
        psw = sharedPreferences.getString("password", "");
        etUser.setText(user);
        etPsw.setText(psw);
    }

    public void onLogin(View view) {
        user = etUser.getText().toString();
        psw = etPsw.getText().toString();
        if (!TextUtils.isEmpty(user) && !TextUtils.isEmpty(psw) && !TextUtils.isEmpty(psw)) {
            login(user, psw);
        } else {
            Toast.makeText(this, "请输入账号和邀请码", Toast.LENGTH_SHORT).show();
        }
    }

    public void onExit(View view) {
        Intent intent = new Intent(this, SmsObserverService.class);
        stopService(intent);
        SmsApplication.exit();
    }

    private void login(final String username, final String password) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。

        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("username", username);//传递键值对参数
        formBody.add("password", password);//传递键值对参数
        final Request request = new Request.Builder()//创建Request 对象。
                .url("http://106.14.210.82/api/login.php")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("登录失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {//回调的方法执行在子线程。
                    try {
                        JSONObject result = new JSONObject(response.body().string());
                        System.out.println(result.toString(2));
                        //{"code":10001,"data":null,"msg":false}
                        int code = result.optInt("code");
                        String msg = result.optString("msg");
                        if (code == 10000) {
                            loginSuccess(username, password);
                            //成功
                            return;
                        } else {
                            //失败
                            showToast(msg);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                showToast("登录失败");
            }
        });
    }

    private void loginSuccess(String username, String password) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putBoolean("isLogin", true);
        editor.apply();
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }
}